
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author user
 */
public class EmettreOrdre extends javax.swing.JFrame {

    private String ordreType;
    private String entreprise;
    private String quantity;
    private String client;
    private boolean selected = false;
    private boolean rempli = false;
    private Object[][] data; // 

    public EmettreOrdre() {
        initComponents();
        this.setResizable(false);
        // Remplissage combobox Nom Client: ne selectionner que les clients du trader concerné ! ************************
        DbManip.remplirComboBoxADeuxChamps(choixClient, "CLIENT where MATRICULE='"+DbManip.traderId+"'", "NOM_CLIENT", "PRENOM_CLIENT", "Choisir un client");
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        valider = new javax.swing.JButton();
        retour = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jPanel1 = new javax.swing.JPanel();
        choixEntreprise = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        choixClient = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        quantite = new javax.swing.JTextField();
        typeOrdre = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        valider.setBackground(new java.awt.Color(255, 255, 255));
        valider.setText("Valider");
        valider.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                validerActionPerformed(evt);
            }
        });

        retour.setBackground(new java.awt.Color(255, 255, 255));
        retour.setText("Annuler");
        retour.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                retourActionPerformed(evt);
            }
        });

        jSeparator1.setBackground(new java.awt.Color(155, 155, 0));
        jSeparator1.setForeground(new java.awt.Color(0, 0, 0));

        jSeparator2.setBackground(new java.awt.Color(150, 150, 0));
        jSeparator2.setForeground(new java.awt.Color(0, 0, 0));

        choixEntreprise.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-- Choisir type et  client--" }));
        choixEntreprise.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                choixEntrepriseMouseReleased(evt);
            }
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                choixEntrepriseMouseClicked(evt);
            }
        });
        choixEntreprise.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                choixEntreprisePopupMenuWillBecomeVisible(evt);
            }
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
        });
        choixEntreprise.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                choixEntrepriseActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        jLabel3.setText("Client");

        choixClient.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                choixClientItemStateChanged(evt);
            }
        });
        choixClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                choixClientActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        jLabel1.setText("Entreprise");

        jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        jLabel4.setText("Quantité");

        quantite.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                quantiteKeyTyped(evt);
            }
        });

        typeOrdre.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--  Choisir un type --", "Vente", "Achat" }));
        typeOrdre.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                typeOrdreItemStateChanged(evt);
            }
        });
        typeOrdre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                typeOrdreActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        jLabel2.setText("Type d'ordre");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(74, 74, 74)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(quantite)
                        .addComponent(choixEntreprise, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(choixClient, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(typeOrdre, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(18, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(typeOrdre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(choixClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(50, 50, 50)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(choixEntreprise, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(36, 36, 36)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(quantite, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(valider, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(137, 137, 137)
                .addComponent(retour, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(157, 157, 157))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
                            .addComponent(jSeparator1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(135, 135, 135)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(retour)
                    .addComponent(valider))
                .addGap(47, 47, 47))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void validerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_validerActionPerformed
        try {
            
            
            ordreType = typeOrdre.getSelectedItem().toString();
            entreprise = choixEntreprise.getSelectedItem().toString();
            if( (entreprise.equals("-- Choisir type et  client--"))||(entreprise.equals("-- Choisir entreprise--")))
            {
            JOptionPane.showMessageDialog(null, "Veuillez choisir une entreprise !", "Attention", JOptionPane.ERROR_MESSAGE);
            return;
            }
            client = choixClient.getSelectedItem().toString();
            quantity = quantite.getText();
            if (!quantity.matches(DbManip.regexDigit)){
                    JOptionPane.showMessageDialog(null, "Le champ quantité doit être entier !", "Attention", JOptionPane.ERROR_MESSAGE);
                    return;
                }
  
            // Controle supplémentaire si le type = Vente : la quantité qoit être < nbre des actions que posséde le Trader
            //  **************** Detreminer l' id à insérer automatiquement *****************
            int id = DbManip.next_Id("ordre", "id_ordre");
            //**************************** Recherche id entreprise afin de chercher id action
            int id_entrep = DbManip.recupererIdDUnchamp("entreprise", "id_entreprise", "NOM_ENTREPRISE", entreprise);
            //**************************** Recherche id action
            int id_action = 0;
            DbManip.requete = "SELECT ID_ACTION FROM ACTION WHERE ID_ENTREPRISE='" + id_entrep + "'";
            DbManip.executer(DbManip.requete);
            while (DbManip.rs.next()) {
                id_action = DbManip.rs.getInt(1);
            }
            // ***** Recupérer id_client Client ********************
            String ch = (String) choixClient.getSelectedItem();
            int id_client = DbManip.recupererIdDedeuxChamps("client", "id_client", "nom_client", "prenom_client", ch); 
            
            
              
                if (ordreType.equals("Vente"))
             {
                 DbManip.requete="select QUANTITY from PORTE_FEUILLE_ACTION where ID_ACTION='"+id_action+"' and "
                         + " ID_PORTE_FEUILLE='"+id_client+"'";
                 DbManip.executer(DbManip.requete);
                 int nb=0; 
                 while(DbManip.rs.next())
                 {
                     nb= DbManip.rs.getInt(1);
                 }
                 
                 
                 DbManip.requete=" select QUANTITE from ordre where STATUT='attente' and TYPE='Vente'"
                         + " and ID_CLIENT='"+id_client+"' and ID_ACTION='"+id_action+"'";
                 DbManip.executer(DbManip.requete);
                 while (DbManip.rs.next())
                 {
                     nb= nb-DbManip.rs.getInt(1);
                 }                
                 
                 if(Integer.parseInt(quantity)>nb)
                 {  
                    String msg="Le nombre des actions à vendre doit être inférieur ou égale à "+String.valueOf(nb); 
                    JOptionPane.showMessageDialog(null, msg, "Attention", JOptionPane.ERROR_MESSAGE);

                    return;
                 }
             }
            //Confirmation finale
            if(JOptionPane.showConfirmDialog(new JFrame(), "Est-ce que vous voulez continuer?"
                    + "", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION) !=0){
                
                return;
            } 

            // *********************** Requete D'insertion ***************************  
            DbManip.requete = "insert into ORDRE (ID_ORDRE,ID_ACTION,ID_CLIENT,TYPE,STATUT,DATE_EMISSION_ORDRE,QUANTITE) VALUES ('" + id + "','" + id_action + "','" + id_client + "','" + ordreType + "','" + "attente" + "',TIMESTAMP '" + DbManip.date + "','" + quantity + "')";
            DbManip.executerUpdate(DbManip.requete);
            
        JOptionPane.showMessageDialog(null, " Ordre émis avec succès !", "Information", JOptionPane.INFORMATION_MESSAGE);
        retourActionPerformed(evt);
        

            //**********************************                     
        } catch (SQLException ex) {
            Logger.getLogger(EmettreOrdre.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_validerActionPerformed

    private void typeOrdreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeOrdreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_typeOrdreActionPerformed

    private void choixClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_choixClientActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_choixClientActionPerformed

    private void choixEntrepriseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_choixEntrepriseActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_choixEntrepriseActionPerformed

    private void typeOrdreItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_typeOrdreItemStateChanged
        choixEntreprise.removeAllItems();
        choixEntreprise.addItem("-- Choisir type et  client--");

        // TODO add your handling code here:
    }//GEN-LAST:event_typeOrdreItemStateChanged

    private void choixEntrepriseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_choixEntrepriseMouseClicked
    }//GEN-LAST:event_choixEntrepriseMouseClicked

    private void choixEntrepriseMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_choixEntrepriseMouseReleased
    }//GEN-LAST:event_choixEntrepriseMouseReleased

    private void choixEntreprisePopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_choixEntreprisePopupMenuWillBecomeVisible
        // TODO add your handling code here:
        if ((typeOrdre.getSelectedItem().toString().equals("--  Choisir un type --"))
                || (choixClient.getSelectedItem().toString().equals("-- Choisir un client--"))) {
            JOptionPane.showMessageDialog(null, "Veuillez choisir un type et/ou un client", "Attention", JOptionPane.ERROR_MESSAGE);
            choixEntreprise.removeAllItems();
            choixEntreprise.addItem("-- Choisir type et  client--");
            return;
        } 
        else {
            choixEntreprise.removeAllItems();
            if ((typeOrdre.getSelectedItem().toString().equals("Achat"))) {
                DbManip.remplirComboBoxAUnChamps(choixEntreprise, "entreprise where NOM_ENTREPRISE != 'Autre'", "NOM_ENTREPRISE", "Choisir entreprise");
            } else {
                try {
                    // type  =  Vente
                    choixEntreprise.addItem("-- Choisir entreprise--");
                    String Idcl = choixClient.getSelectedItem().toString();
                    Idcl = String.valueOf(DbManip.recupererIdDedeuxChamps("client", "id_client", "NOM_CLIENT", "prenom_client", Idcl));
                  
                    DbManip.requete = "select action.ID_ENTREPRISE from action inner join PORTE_FEUILLE_ACTION on action.id_action=PORTE_FEUILLE_ACTION.id_action"
                            + " where PORTE_FEUILLE_ACTION.ID_PORTE_FEUILLE='" + Idcl + "'";
                   
                    DbManip.executer(DbManip.requete);
                    DbManip.afficher();
                    int m = DbManip.rsmd.getColumnCount();
                    DbManip.rs.last();
                    int n = DbManip.rs.getRow();
                    int i = 0, j = 0;
                    DbManip.rs.beforeFirst();
                    data = new Object[n][m];
                    while (DbManip.rs.next()) {
                        String id_entreprise = DbManip.rs.getString(1);
                        data[i][0] = id_entreprise;
                        i++;
                    }
                    //Remplissage Choix entreprise pour l'affichage !!
                    for (int l = 0; l < n; l++) {
                       String entrep =DbManip.recupererChampDUnId("entreprise", "nom_entreprise", "id_entreprise", data[l][0].toString());
                       choixEntreprise.addItem(entrep);
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(EmettreOrdre.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }//GEN-LAST:event_choixEntreprisePopupMenuWillBecomeVisible

    private void choixClientItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_choixClientItemStateChanged
        choixEntreprise.removeAllItems();
        choixEntreprise.addItem("-- Choisir type et  client--");
        // TODO add your handling code here:
    }//GEN-LAST:event_choixClientItemStateChanged

    private void quantiteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_quantiteKeyTyped
   if ( quantite.getText().length() >= 10 )
        	evt.consume();
        // TODO add your handling code here:
    }//GEN-LAST:event_quantiteKeyTyped

    private void retourActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_retourActionPerformed
        typeOrdre.setSelectedIndex(0);
        choixEntreprise.setSelectedIndex(0);
        choixClient.setSelectedIndex(0);
        quantite.setText("");


    }//GEN-LAST:event_retourActionPerformed

    /**
     * @param args the command line arguments
     */
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox choixClient;
    private javax.swing.JComboBox choixEntreprise;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextField quantite;
    private javax.swing.JButton retour;
    private javax.swing.JComboBox typeOrdre;
    private javax.swing.JButton valider;
    // End of variables declaration//GEN-END:variables
}
